package com.hotel.wallet.controller;


import cn.hutool.core.convert.NumberWithFormat;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotel.common.config.SystemConfig;
import com.hotel.common.util.JwtUtil;
import com.hotel.common.vo.R;
import com.hotel.user.entity.User;
import com.hotel.user.entity.UserLog;
import com.hotel.wallet.mapper.UserLogMapper;
import com.hotel.wallet.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 用户日志表 前端控制器
 * </p>
 *
 * @author zhy
 * @since 2024-06-19
 */
@RestController
@RequestMapping("/user")
public class UserLogController {

    @Autowired
    private UserLogMapper userLogMapper;

    @Autowired
    private UserMapper userMapper;


    @RequestMapping("/my")
    public R getAccount(HttpServletRequest request) {

        // 获取id
        // 前端没有传id，通过token得到id需要HttpServletRequest
        String token = request.getHeader(SystemConfig.HEADER_TOKEN);
        // 解析token得到id(token是由user.getId(), user.getAccount(), user.getPhone()组成)
        Integer id = ((NumberWithFormat) JwtUtil.parseToken(token, "id")).intValue();


        // 从user_log中通过user_id获得用户信息
        QueryWrapper<UserLog> userLogQueryWrapper = new QueryWrapper<>();
        userLogQueryWrapper.eq("user_id",id);

        UserLog userLog = userLogMapper.selectOne(userLogQueryWrapper);

        // 通过userLog的手机号在user表中查询account
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("phone",userLog.getMobile());

        User user = userMapper.selectOne(userQueryWrapper);

        if (user == null) {
            return R.fail("用户未登陆");
        }
        return R.ok(user);

    }

}

